package org.zoomdev.zoom.dao.adapters.result;

import org.zoomdev.zoom.common.io.Io;
import org.zoomdev.zoom.common.json.JSON;
import org.zoomdev.zoom.dao.DaoException;
import org.zoomdev.zoom.dao.adapters.ResultSetAdapter;

import java.io.InputStream;
import java.lang.reflect.Type;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BlobJsonResultSetAdapter implements ResultSetAdapter {

    private final Type type;

    public BlobJsonResultSetAdapter(Type type) {
        this.type = type;
    }

    @Override
    public Object getObject(ResultSet rs, int columnIndex) throws SQLException {
        InputStream is = null;
        try {
            Blob blob = rs.getBlob(columnIndex);
            is = blob.getBinaryStream();
            return JSON.parse(is, type);
        } catch (SQLException e) {
            throw new DaoException(e);
        } finally {
            Io.close(is);
        }
    }
}
